#include <QTextCodec>

#include "nconfig.h"
#include "nmusicfile.h"

NMusicFile::NMusicFile(TagLib::FileRef *f, QByteArray na, QByteArray ar, QByteArray al, QByteArray cm, QString pa) :
    file(f), _bname(na), _bartist(ar), _balbum(al), _bcomment(cm), _path(pa) {
	Q_ASSERT(f);
}

NMusicFile::~NMusicFile(){
    delete file;
}

QString NMusicFile::name(void){
    return _name;
}

QString NMusicFile::artist(void){
    return _artist;
}

QString NMusicFile::album(void){
    return _album;
}

QString NMusicFile::comment(void){
    return _comment;
}

QString NMusicFile::path(void){
    return _path;
}

void NMusicFile::setEncoding(QTextCodec *x){
    Q_ASSERT(x);
    _name = x->toUnicode(_bname);
    _artist = x->toUnicode(_bartist);
    _album = x->toUnicode(_balbum);
    _comment = x->toUnicode(_bcomment);
}

NMusicFile *NMusicFile::load(const QString &path){    
    TagLib::FileRef *file = new TagLib::FileRef(path.toUtf8().constData());
    
    if(!file->isNull() && file->tag()) {
	TagLib::Tag *tag = file->tag();
	
	NMusicFile *f = new NMusicFile(file,
					QByteArray(tag->title().toCString()), 
					QByteArray(tag->artist().toCString()),
					QByteArray(tag->album().toCString()),
					QByteArray(tag->comment().toCString()),
					   path);
	Q_ASSERT(f);
	return f;
    } else
	return NULL;
}

bool NMusicFile::save(){
    TagLib::Tag *t = file->tag();
   
    t->setTitle(TagLib::String(_name.toUtf8().constData(), TagLib::String::UTF8));
    t->setArtist(TagLib::String(_artist.toUtf8().constData(), TagLib::String::UTF8));
    t->setAlbum(TagLib::String(_album.toUtf8().constData(), TagLib::String::UTF8));
    t->setComment(TagLib::String(_comment.toUtf8().constData(), TagLib::String::UTF8));
       
    file->save();
    
    return true;
}
